﻿using ERCS.Model;
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;

namespace ERCS.ViewModel.HomeVMs
{
    public class FrontPageVM : BaseVM
    {
        public Dictionary<PatientStatusEnum,int> ChinaInfo { get; set; }
        public Dictionary<DateTime,int> WorldInfo { get; set; }

        public Dictionary<string,int> MapInfo { get; set; }

        protected override void InitVM()
        {
            ChinaInfo = ReadFromCache<Dictionary<PatientStatusEnum, int>>("chinainfo", () =>
            {
                return DC.Set<Patient>().DPWhere(LoginUserInfo.DataPrivileges, x => x.LocationId).GroupBy(x => x.Status).Select(x => new { sta = x.Key, count = x.Count() }).ToDictionary(x => x.sta.Value, x => x.count);
            }, 1800);
            //ChinaInfo = DC.Set<Patient>().DPWhere(LoginUserInfo.DataPrivileges,x=>x.LocationId).GroupBy(x => x.Status).Select(x => new { sta = x.Key, count = x.Count() }).ToDictionary(x => x.sta.Value, x => x.count);
            foreach (var status in Enum.GetValues(typeof(PatientStatusEnum)))
            {
                PatientStatusEnum s = Enum.Parse<PatientStatusEnum>(status.ToString());
                if (ChinaInfo.ContainsKey(s) == false)
                {
                    ChinaInfo[s] = 0;
                }
            }
            var temp = DC.Set<Patient>().GroupBy(x => x.Location.Parent.Parent.Name).Select(x => new { sheng = x.Key, count = x.Count() }).OrderByDescending(x => x.count).ToList();
            MapInfo = temp.ToDictionary(x => x.sheng.Replace("省", "").Replace("市", "").Replace("自治区", "").Replace("回族", "").Replace("壮族", "").Replace("维吾尔", ""), x => x.count);

            using (var newdc = ConfigInfo.ConnectionStrings.Where(x=>x.Key == "csse").FirstOrDefault().CreateDC())
            {
                WorldInfo = newdc.Set<Csse>().GroupBy(x => x.Date, x => x.ConfirmedCase).Select(x=>new { date = x.Key, count = x.Sum() }).OrderBy(x => x.date).ToDictionary(x => x.date, x => x.count);
                
            }
        }

        protected T ReadFromCache<T>(string key, Func<T> setFunc, int? timeout = null)
        {
            if (Cache.TryGetValue(key, out T rv) == false || rv == null)
            {
                T data = setFunc();
                if (timeout == null)
                {
                    Cache.Add(key, data);
                }
                else
                {
                    Cache.Add(key, data, new DistributedCacheEntryOptions()
                    {
                        SlidingExpiration = new TimeSpan(0, 0, timeout.Value)
                    });
                }
                return data;
            }
            else
            {
                return rv;
            }
        }

    }
}
